package com.umeox.watch.moto.pedometer.data;


import static com.umeox.watch.moto.pedometer.util.ICache.KEY_STEP_COUNT_TOTAL;

import android.os.AsyncTask;
import android.util.Log;

import com.umeox.moto.common.log.Logger;
import com.umeox.watch.moto.dataservice.interfaces.IPullApiClient;
import com.umeox.watch.moto.dataservice.interfaces.IPushApiClient;
import com.umeox.watch.moto.dataservice.proxy.PullApiClientProxy;
import com.umeox.watch.moto.dataservice.proxy.PushApiClientProxy;
import com.umeox.watch.moto.pedometer.BuildConfig;
import com.umeox.watch.moto.pedometer.base.PedometerDBHelper;
import com.umeox.watch.moto.pedometer.util.CacheImpl;
import com.umeox.watch.moto.pedometer.util.ICache;
import com.umeox.watch.moto.pedometer.util.LogUtils;
import com.umeox.watch.moto.pedometer.util.StepManager;

import org.greenrobot.eventbus.EventBus;

public class PedometerNodeData implements PedometerDataSource {

    public static final String KEY_UPLOAD_LAST_STEPS = "upload_step_counts";
    public static final String KEY_SAVE_LAST_STEPS = "save_step_counts";
    public static final int SENSOR_MAX_VALUE = 30000;
    private PedometerContract.Presenter mPresenter;
    private StepManager mStepManager;
    private static final String TAG = "PedometerData";
    private IPullApiClient pullApiClient;
    private IPushApiClient pushApiClient;
    private int mLastStepCounts;
    private final ICache mCache;
    private int mCacheStepCount;


    public PedometerNodeData(PedometerContract.Presenter presenter) {
        mPresenter = presenter;
        mStepManager = StepManager.getInstance();
        mCache = CacheImpl.getInstance();
        mCacheStepCount = mCache.get(KEY_STEP_COUNT_TOTAL, 0);

    }

    @Override
    public void load() {
        final int stepCounts = mStepManager.getStepCounts() + mCacheStepCount;
        if(BuildConfig.DEBUG){
            Log.w(TAG, "load: " + mLastStepCounts + " cur " + stepCounts + " CacheStepCount " + mCacheStepCount);
        }
        if (stepCounts != mLastStepCounts) {
            if (stepCounts - mCacheStepCount >= SENSOR_MAX_VALUE) {
                StepManager.getInstance().resetSensorFlag();
                mCache.put(KEY_STEP_COUNT_TOTAL, stepCounts);
                mCacheStepCount = stepCounts;
            }
            mLastStepCounts = stepCounts;
            mPresenter.onStepCountChange(stepCounts);
        }
    }


    /**
     * 计步数据上传
     */
    @Override
    public void uploadStepCount() {

        final int stepCounts = mStepManager.getStepCounts() + mCacheStepCount;
        final int lastStepCount = mCache.get(KEY_UPLOAD_LAST_STEPS, -1);
        if (lastStepCount == stepCounts) {
            return;
        }

        mCache.put(KEY_UPLOAD_LAST_STEPS, stepCounts);
        if (pullApiClient == null) {
            pullApiClient = PullApiClientProxy.fetchBinder();
        }
        try {
            pullApiClient.uploadStep(stepCounts);
        } catch (Exception e) {
            Log.w(TAG, "上传计步数据失败 : ", e);
        }

    }

    @Override
    public void saveStepCount() {
        final int stepCounts = mStepManager.getStepCounts() + mCacheStepCount;
        final int lastStepCount = mCache.get(KEY_SAVE_LAST_STEPS, -1);
        if(BuildConfig.DEBUG){
            Log.d(TAG, "currentStepCount: " + stepCounts + " lastSaveStepCount: " + lastStepCount);
        }
        if (lastStepCount == stepCounts) {
            return;
        }
        mCache.put(KEY_SAVE_LAST_STEPS, stepCounts);
        try {
            PedometerDBHelper.getInstance().insertOrUpdateStep(stepCounts);
        } catch (Exception e) {
            if(BuildConfig.DEBUG){
                Log.w(TAG, "PedometerData saveStepCount: ", e);
            }
        }
    }

    @Override
    public void getStepInfo() {
        if (pushApiClient == null) {
            pushApiClient = PushApiClientProxy.fetchBinder();
        }
        AsyncTask.execute(() -> {
            try {
                pushApiClient.requestGetStepInfo();
            } catch (Exception e) {
                Log.d(TAG, "获取计步数据失败:", e);
            }
        });
    }

    @Override
    public void onCreate() {

    }

    @Override
    public void onDestroy() {

    }

    @Override
    public void saveTotalStepCount() {
        final int curStepCount = StepManager.getInstance().getStepCounts() + mCacheStepCount;
        Logger.e(TAG,"saveTotalStepCount=" + curStepCount);
        LogUtils.saveLog("-->saveTotalStepCount=" + curStepCount);
        mCache.put(KEY_STEP_COUNT_TOTAL, curStepCount);
        PedometerDBHelper.getInstance().insertOrUpdateStep(curStepCount);
    }

    @Override
    public void resetAndSaveStepCount(int currentMillis, int saveTimeMillis) {
        Logger.e(TAG,"==========resetAndSaveStepCount=============");
        LogUtils.saveLog("-->resetAndSaveStepCount");
        ICache cache = CacheImpl.getInstance();
        StepManager stepManager = StepManager.getInstance();
        cache.put(ICache.KEY_STEP_TIME, currentMillis);
        final int stepCounts = stepManager.getStepCounts();
        final int count = cache.get(KEY_STEP_COUNT_TOTAL, 0);
        PedometerDBHelper.getInstance().insertOrUpdateStep(saveTimeMillis,stepCounts+count);
        stepManager.resetSensorFlag();
        cache.remove(KEY_STEP_COUNT_TOTAL);
        mCacheStepCount = 0;
        EventBus.getDefault().removeAllStickyEvents();
    }

}
